﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Practices.Prism.Events;
using SailHero.Soft.FrameWork.Models;
using UI.Web.SL.Demo.Infrastructure;
using UI.Web.SL.Demo.Infrastructure.Events;
using UI.Web.SL.Demo.RIAServices.Web;


namespace UI.Web.SL.Demo.SysAdmin.Pages.Sys
{
    public partial class MenuLE : BasePage
    {
        public MenuLE()
        {
            InitializeComponent();
        }
        private IEventAggregator _eventAggregator;
        private SysAdminDContext _sysadminDContext = new SysAdminDContext();

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {            
            if (IsLoaded)
            {
                return;
            }
            InitMenuTree();
            InitTypeCB();
        }
        /// <summary>
        /// 构造菜单路径的combo box
        /// </summary>
        void InitTypeCB()
        {
            var tys = Application.Current.GetType().Assembly.GetTypes().ToList();

           
            var results = tys.Where(m =>  m.IsPublic
                                            && m.FullName.StartsWith("UI.Web.SL.Demo.SysAdmin.Pages")
                                            && !m.FullName.EndsWith(".BasePage"))
                             .Select(m=>GetMenName(m.FullName))
                             .ToList();
            results.Insert(0,"请选择");
            MenuUrlCB.ItemsSource = results;
            MenuUrlCB.UpdateLayout();
            MenuUrlCB.SelectedIndex = 0;
        }

        string GetMenName(string menuFullName)
        {
            if(string.IsNullOrEmpty(menuFullName))
            {
                return "";
            }
            string path = "UI.Web.SL.Demo.SysAdmin.";
            int index = menuFullName.IndexOf(path);
            if(index>=0)
            {
                return menuFullName.Substring(path.Length, menuFullName.Length - path.Length);
            }
            return "";
        }

        /// <summary>
        /// 构造父级菜单的combo box
        /// </summary>
        /// <param name="tMenu"></param>
        void InitParentMenu(IEnumerable<MenuInfo> tMenu)
        {
            var rs = tMenu.ToList();
            var TM = new MenuInfo();
            TM.MenuName = "请选择";
            TM.Id = Guid.Empty;
            rs.Insert(0, TM);
            TMenuCB.ItemsSource = rs;
            TMenuCB.SelectedIndex = 0;
        }
        /// <summary>
        /// 构造菜单树
        /// </summary>
        void InitMenuTree()
        {
            var tMenu = Common.ViewUtility.AllMenu
                    .Where(m => m.ParentId == Guid.Empty)
                    .OrderBy(m=>m.OrderNum);
            InitParentMenu(tMenu);
            foreach (var tm in tMenu)
            {
                var ttvi = new TreeViewItem();
                ttvi.Header = tm.MenuName;
                ttvi.DataContext = tm;
                if (MenuTV.Items.Count < 1)
                {
                    MenuFormG.DataContext = tm;
                    ttvi.IsSelected = true;
                }
                ttvi.IsExpanded = true;
                MenuTV.Items.Add(ttvi);
                var sMenu = Common.ViewUtility.AllMenu
                        .Where(m => m.ParentId == tm.Id)
                        .OrderBy(m => m.OrderNum);
                foreach (var sm in sMenu)
                {
                    var stvi = new TreeViewItem();
                    stvi.Header = sm.MenuName;
                    stvi.DataContext = sm;
                    ttvi.Items.Add(stvi);                    
                }
            }
        }
        /// <summary>
        /// 菜单树 选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuTV_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var item = MenuTV.SelectedItem as TreeViewItem;
            var menuObj = item.DataContext as MenuInfo;
            var fobj = Common.Utility.DeepCopy(menuObj);
            MenuFormG.DataContext = fobj;
            var parent = Common.ViewUtility.AllMenu
                       .Where(m => m.Id == menuObj.ParentId)
                       .FirstOrDefault();
            TMenuCB.SelectedItem = (parent == null ? TMenuCB.Items.FirstOrDefault() : parent);
            MenuUrlCB.SelectedItem = (string.IsNullOrEmpty(menuObj.Url) ? "请选择" : menuObj.Url);
        }
        /// <summary>
        /// 增加事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddBTN_Click(object sender, RoutedEventArgs e)
        {
            var obj = MenuFormG.DataContext as MenuInfo;
            if (FormHasError(MenuFormG))
            {
                Common.ViewUtility.Alert("数据有误不能提交");
                return;
            }
            
           
            obj.Id = Guid.NewGuid();
            obj.ParentId = (TMenuCB.SelectedItem as MenuInfo).Id;

            _sysadminDContext.MenuInfos.Add(obj);
            _sysadminDContext.SubmitChanges(AddMenuCompleted, obj);
        }


        private void AddMenuCompleted(SubmitOperation operation)
        {
            
            if (operation.IsComplete)
            {
                Common.ViewUtility.Alert("增加成功");
                Common.ViewUtility.AllMenu.Add((MenuInfo)operation.UserState);
                Reload();
            }
        }


        private void UpdateMenuCompleted(SubmitOperation operation)
        {

            if (operation.IsComplete)
            {
                MenuInfo obj = (MenuInfo) operation.UserState;
                Common.ViewUtility.Alert("修改成功");
                var old = Common.ViewUtility.AllMenu.Where(m => m.Id == obj.Id).FirstOrDefault();
                Common.ViewUtility.AllMenu.Remove(old);
                Common.ViewUtility.AllMenu.Add(obj);
                Reload();
            }
        }


        private void DeleteMenuCompleted(SubmitOperation operation)
        {

            if (operation.IsComplete)
            {
                MenuInfo obj = (MenuInfo)operation.UserState;
                Common.ViewUtility.Alert("删除成功");
                var old = Common.ViewUtility.AllMenu.Where(m => m.Id == obj.Id).FirstOrDefault();
                Common.ViewUtility.AllMenu.Remove(old);
                Reload();
            }
        }

        private void EditBTN_Click(object sender, RoutedEventArgs e)
        {
            var obj = MenuFormG.DataContext as MenuInfo;
            if (FormHasError(MenuFormG))
            {
                Common.ViewUtility.Alert("数据有误不能提交");
                return;
            }
            obj.ParentId = (TMenuCB.SelectedItem as MenuInfo).Id;
            string nm = obj.MenuName;
            obj.MenuName = "";
            _sysadminDContext.MenuInfos.Attach(obj);
            obj.MenuName = nm;
            _sysadminDContext.SubmitChanges(UpdateMenuCompleted, obj);
        }

        private void DelBTN_Click(object sender, RoutedEventArgs e)
        {             
            var askResult = Common.ViewUtility.Ask("确实要删除此菜单吗？");
            if (MessageBoxResult.Cancel == askResult)
            {
                return;
            }
            var obj = MenuFormG.DataContext as MenuInfo;

            _sysadminDContext.MenuInfos.Attach(obj);
            _sysadminDContext.MenuInfos.Remove(obj);
            _sysadminDContext.SubmitChanges(DeleteMenuCompleted, obj);
        }
    }
}
